題目:給定一陣列和目標值,回傳陣列中兩數相加等於目標值的陣列位址,數值不可重複使用。(假設陣列中一定有兩數相加等於目標值)
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
解法:
建立檢查陣列,把補數設為key,value紀錄當前陣列位址,當補數的key出現,則回傳先前紀錄對應補數的陣列位址以及當前陣列位址。
def two_sum(nums, target)
check ={}
index = 0
nums.each do |num|
if check[num]
return[check[num],index]
end
complement = target - num
check[complement] = index
index += 1
end
end